package com.mazaiting.web.wrapper;

import cn.hutool.core.io.IoUtil;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @author mazaiting
 * @description request重复读包装类
 * @date 2022/8/1
 */
public class WrappedHttpServletRequest extends HttpServletRequestWrapper {
    /**
     * 原始字节内容
     */
    private final byte[] bytes;
    /**
     * 包装流
     */
    private final WrappedServletInputStream wrappedServletInputStream;

    public WrappedHttpServletRequest(HttpServletRequest request) throws IOException {
        super(request);
        // 读取流中的请求参数并保存到bytes里
        bytes = IoUtil.readBytes(request.getInputStream());
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        this.wrappedServletInputStream = new WrappedServletInputStream(byteArrayInputStream);
        reWriteInputStream();
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return wrappedServletInputStream;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(wrappedServletInputStream));
    }

    /**
     * 获取POST参数
     * @return
     */
    public String getRequestBody() throws UnsupportedEncodingException {
        return new String(bytes, this.getCharacterEncoding());
    }

    /**
     * 重写输出流
     */
    private void reWriteInputStream() {
        wrappedServletInputStream.setStream(new ByteArrayInputStream(ObjectUtils.isEmpty(bytes) ? new byte[0] : bytes));
    }


}
